package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
)

func init() {
	godotenv.Load()
}

func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = "80"
	}

	router := gin.Default()

	router.GET("/hello", func(c *gin.Context) {
		rel := SvcTest("http://192.168.13.81:32511/my/env")
		c.String(200, rel)
	})

	router.GET("/", func(c *gin.Context) {
		SvcTest("http://service-myapp:80/env")

		SvcTest("http://10.96.35.163:80/env")

		SvcTest("http://service-youapp:80/env")

		SvcTest("http://10.98.119.4:80/env")

		SvcTest("http://10.244.102.168:80/env")
		c.String(200, "Hello World")
	})

	router.GET("/env", func(c *gin.Context) {
		c.String(200, "Hello %s", os.Getenv("NAME"))
	})

	router.GET("/svc", func(c *gin.Context) {
		SvcTest("http://10.96.35.163:80/env")
		SvcTest("http://10.98.119.4:80/env")

		SvcTest("http://10.244.102.168:80/env")
		SvcTest("http://service-myapp:80/env")

		SvcTest("http://service-youapp:80/env")

		c.String(200, "Hello svc")
	})
	log.Print(" port: ", port)
	router.Run(":" + port)
}

func SvcTest(url string) string {
	getRelIp := GetJson(url, "nil")
	fmt.Printf(" GetJson(\"%s\",\"nil\") %s", url, getRelIp)
	log.Print(" GetJson(\"{}\",\"nil\") {}", url, "=>", getRelIp)
	return getRelIp
}

/**
发送的POST请求 需要设置header
Testner 20210123
*/
func PostJson(url string, bodyJson string, authorization string) string {

	contentType := "application/json"

	req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(bodyJson)))

	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", authorization))
	req.Header.Set("Content-Type", contentType)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}

	byts, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	if err != nil {
		log.Fatal(err)
	}
	return (string(byts))
}

/**
发送的GET请求 需要设置header
Testner 20210123
*/
func GetJson(url string, authorization string) string {

	contentType := "application/json"

	req, err := http.NewRequest("GET", url, nil)

	if err != nil {
		log.Fatal(err)
		return url + " error 1"
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", authorization))
	req.Header.Set("Content-Type", contentType)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
		return url + " error 2"
	}

	byts, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	if err != nil {
		log.Fatal(err)
		return url + " error 3"
	}
	return (string(byts))
}
